package c2.cross.business.championrace.sub;

import c2.cross.business.base.CrossSubModule;
import c2.cross.business.championrace.ChampionRaceModule;
import cate.game.event.championrace.ChampionRaceTimerEvent;
import cate.game.pvp.championrace.data.ChampionRaceMsg;
import cate.game.pvp.championrace.data.ChampionRaceSpec;
import cate.game.res.Pair;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@Slf4j
public class ChampionRaceMsgModule extends CrossSubModule<ChampionRaceModule> {
    private final List<Pair<ChampionRaceSpec, ChampionRaceTimerEvent>> specEvents = new LinkedList<>();

    /**
     * 同步玩法信息事件
     *
     * @param event 事件
     */
    public synchronized void dispatchTimerEvent(ChampionRaceSpec spec, ChampionRaceTimerEvent event) {
        try {
            addSpecCache(spec.copy(), event);
            useRpcSend().fireAndForgetGameInCrossTemplate(ChampionRaceMsg.TIMER_EVENT,
                    parent.code(),
                    event);
        } catch (Exception e) {
            log.error("", e);
        }
    }

    private void addSpecCache(ChampionRaceSpec spec, ChampionRaceTimerEvent event) {
        log.info("spec cache添加了一个事件，event={}", event);
        specEvents.add(new Pair<>(spec, event));
        if (specEvents.size() >= 100) {
            specEvents.remove(0);
        }
    }

    public synchronized List<ChampionRaceTimerEvent> getSpecEvents(ChampionRaceSpec spec) {
        List<ChampionRaceTimerEvent> events = new ArrayList<>();
        for (Pair<ChampionRaceSpec, ChampionRaceTimerEvent> pair : specEvents) {
            if (pair.v.getSeason() >= spec.getSeason() && pair.k.compareTo(spec) > 0) {
                events.add(pair.v);
            }
        }
        return events;
    }
}
